package com.littleken.foodieApi.controller;

import com.littleken.foodieCommon.Response.ErrorCode;
import com.littleken.foodieCommon.Response.ServerResponse;
import com.littleken.foodieCommon.Utils.BeanCopierUtil;
import com.littleken.foodieCommon.Utils.BeanValidator;
import com.littleken.foodieCommon.Utils.BeanValidatorUtils;
import com.littleken.foodieCommon.Utils.CookieUtils;
import com.littleken.foodieCommon.Utils.JsonUtils;
import com.littleken.foodieCommon.constant.Constant;
import com.littleken.foodiePojo.bo.InsertUserBO;
import com.littleken.foodiePojo.bo.LoginUserBO;
import com.littleken.foodiePojo.domain.UsersDO;
import com.littleken.foodiePojo.vo.UsersVO;
import com.littleken.foodieService.UsersService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/*
 * user controller 用户查询 注册 删除 查重 登录 登出操作
 * Create by littleken on 2020/11/20 17:13
 */
@RestController
@RequestMapping("/user")
public class UsersController {

    @Resource
    private UsersService usersService;

    @ApiOperation(value = "根据用户id查询用户信息", notes = "根据用户id查询用户信息", httpMethod = "GET")
    @GetMapping("/getUser/{id}")
    public ServerResponse<UsersVO> get(@PathVariable String id) {
        UsersDO usersDO = usersService.getUser(id);
        return usersDO != null ? ServerResponse.success(BeanCopierUtil.copy(usersDO, UsersVO.class))
                : ServerResponse.fail(ErrorCode.RECORD_NOT_EXIST);
    }

    @ApiOperation(value = "查询所有用户", notes = "查询所有用户", httpMethod = "GET")
    @GetMapping("/getAllUsers")
    public ServerResponse<List<UsersVO>> getAllUsers() {
        List<UsersDO> usersDOS = usersService.userList();
        return ServerResponse.success(BeanCopierUtil.copyList(usersDOS, UsersVO.class));
    }

    @ApiOperation(value = "新用户注册", notes = "新用户注册", httpMethod = "POST")
    @PostMapping("/insertUser")
    public ServerResponse<String> insertUser(@RequestBody InsertUserBO insertUserBO) {
        //常规校验
        BeanValidator.check(insertUserBO);
        return usersService.insertUser(insertUserBO);
    }

    @ApiOperation(value = "更新用户信息", notes = "更新用户信息", httpMethod = "POST")
    @PostMapping("/updateUser")
    public ServerResponse<String> updateUser(@RequestBody UsersVO usersVO) {
        if (usersVO == null || StringUtils.isBlank(usersVO.getId())) {
            return ServerResponse.fail(ErrorCode.PARAMS_INVALID);
        }
        UsersDO checkUserExist = usersService.getUser(usersVO.getId());
        if (checkUserExist == null) {
            return ServerResponse.fail(ErrorCode.PARAMS_INVALID);
        }
        UsersDO usersDO = BeanCopierUtil.copy(usersVO, UsersDO.class);
        String userId = usersService.updateUser(usersDO);
        return StringUtils.isBlank(userId) ?
                ServerResponse.success(userId) :
                ServerResponse.fail(ErrorCode.SQL_EXECUTE_ERR);
    }

    @ApiOperation(value = "删除用户", notes = "删除用户", httpMethod = "GET")
    @GetMapping("/deleteUser/{id}")
    public ServerResponse<Object> deleteUser(@PathVariable String id) {
        if (StringUtils.isBlank(id)) {
            return ServerResponse.fail(ErrorCode.PARAMS_INVALID);
        }
        return usersService.deleteUser(id);
    }

    @ApiOperation(value = "查询用户名是否已存在", notes = "查询用户名是否已存在", httpMethod = "POST")
    @PostMapping("/queryUserNameIsExist")
    public ServerResponse<Object> queryUserNameIsExist(@RequestBody UsersVO usersVO) {
        if (usersVO == null || StringUtils.isBlank(usersVO.getUsername())) {
            return ServerResponse.fail(ErrorCode.PARAMS_INVALID);
        }
        boolean result = usersService.queryUserNameIsExist(usersVO.getUsername());
        return !result ? ServerResponse.success("用户名可用") : ServerResponse.fail(ErrorCode.USER_IS_EXIST);
    }

    @PostMapping("/userLogin")
    public ServerResponse<Object> userLogin(@RequestBody LoginUserBO loginUserBO,
                                            HttpServletRequest request,
                                            HttpServletResponse response) {
        BeanValidator.check(loginUserBO);
        UsersVO userInfo = usersService.userLogin(loginUserBO.getUsername(), loginUserBO.getPassword());
        if (userInfo != null) {
            //user cookie key
            //cookie存的是string 要讲对象先转成json
            // true 设置加密，这样浏览器中的cookie就难破解
            CookieUtils.setCookie(request,response, Constant.COOKIE_NAME,
                    JsonUtils.objectToJson(userInfo),true);
        }
        return userInfo != null ? ServerResponse.success("登录成功") : ServerResponse.fail(ErrorCode.PASSWORD_ERROR);
    }

    @PostMapping("/userLogin/test")
    public ServerResponse<Object> userLoginTest(@RequestBody @Valid LoginUserBO loginUserBO,
                                                BindingResult result){
        if (result.hasErrors()) {
            Map<String, String> errorMap = BeanValidatorUtils.getErrors(result);
            return ServerResponse.fail(ErrorCode.PARAMS_INVALID,errorMap.toString());
        }
        return ServerResponse.success();
    }


    @GetMapping("/userLogout")
    public ServerResponse<Object> userLogout( HttpServletRequest request,
                                              HttpServletResponse response){
        CookieUtils.deleteCookie(request,response,Constant.COOKIE_NAME);
        return ServerResponse.success();
    }

    @PostMapping("/uploadUserFace")
    public ServerResponse uploadFace( MultipartFile file,
                                      HttpServletRequest request,
                                      HttpServletResponse response){
        return ServerResponse.success();
    }


}
